package com.example.shop;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.utils.CommodityDataUtils;

public class addCommodity extends AppCompatActivity {
    EditText name,price,profile;
    Button bt_add,submit;
    String imagePath = "";
    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_commodity);
        name = findViewById(R.id.item_name);
        price = findViewById(R.id.price);
        profile = findViewById(R.id.item_profile);
image =findViewById(R.id.imageView);
        bt_add = findViewById(R.id.addImage);
        submit = findViewById(R.id.submit);
        bt_add.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, 2);
        });
        submit.setOnClickListener(view -> {
            CommodityDataUtils commodityDataUtils = CommodityDataUtils.getInstance(addCommodity.this);
            Commodity commodity = new Commodity();

            commodity.item_name = name.getText().toString();
            commodity.item_price = price.getText().toString();
            commodity.item_profile = profile.getText().toString();
            commodity.item_image = imagePath;
            if(commodity.item_name.equals("")||commodity.item_price.equals("")||commodity.item_profile.equals("")||commodity.item_image.equals(""))
            {
                Toast.makeText(addCommodity.this,"信息提交不完整",Toast.LENGTH_SHORT).show();
            }
            else
            {
                commodityDataUtils.addCommodity(commodity);
                Intent intent = new Intent(addCommodity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径

                Uri uri = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                imagePath = picturePath;
                image.setImageURI(Uri.parse(picturePath));
                cursor.close();

            }
        }
    }
}